<?php

class AuthorizationController extends AdminController {

	const MODEL_CLASS_NAME = 'User';

	public $disableScripts = array();
	public $email;

	public function allowedActions() {
		return "*";
	}

	public function actionError() {

		$error = Yii::app()->errorHandler->error;
		if ($error) {
			if (!Yii::app()->request->isAjaxRequest) {
				if (!param('debugMode')) {
					$error['message'] = t('MSG_SORRY_INCONVENIENCE', 'messages');
				}
				$this->render('error', $error);
			} else {
				if (!param('debugMode')) {
					$error['message'] = t('MSG_SORRY_INCONVENIENCE', 'messages');
				}

				echo CJSON::encode(array(
		    'status' => MsgType::ERROR,
		    'content' => $error['message'],
				));

				// Stop script execution
				Yii::app()->end();
			}
		}
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin() {
		if (!Yii::app()->user->isGuest)
		$this->redirect(Yii::app()->homeUrl);

		$model = new LoginForm('login');

		// if it is ajax validation request
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if (isset($_POST['LoginForm'])) {
			$model->attributes = $_POST['LoginForm'];

			if ($model->validate('login') && $model->login()) {
				$user = User::model()->findByPk(Yii::app()->user->id);
				$user->latest_login = date(LGConstant::DATE_FORMAT_FOR_DATABASE);
				$user->auth_assignments = $user->getAuth_Assignments();
				if ($user->update()) {
					$this->redirect(Yii::app()->user->returnUrl);
				}
			}
		}

		// display the login form
		$this->layout = 'login';
		$this->render('login', array('model' => $model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout() {
		Yii::app()->user->logout();
		$this->redirect(url('authorization/login'));
	}

	function actions() {
		return array(
	    'changepassword' => array(
		'class' => 'lib.components.actions.UpdateAction',
		'modelClass' => AuthorizationController::MODEL_CLASS_NAME,
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_USER', 'authorization'))))
		),
		);
	}

	public function stopJS() {
		$defaultDisableScripts = array(
	    'jquery.js',
	    'jquery.min.js',
	    'jquery-ui.min.js'
	    );

	    // Merge with user set scripts which should be disabled
	    if (is_array($this->disableScripts)) {
	    	$this->disableScripts = CMap::mergeArray(
	    	$defaultDisableScripts, $this->disableScripts);
	    }
	    else
	    throw new CException(Yii::t($this->tCategory, t('MSG_DISABLE_SCRIPT', 'messages')));

	    // Disable scripts
	    foreach ($this->disableScripts as $script)
	    Yii::app()->clientScript->scriptMap[$script] = false;
	}

	public function actionChangePassword() {
		$this->stopJS();
		$model = new ChangePasswordForm();
		if (isset($_POST['ChangePasswordForm'])) {
			$model->attributes = $_POST['ChangePasswordForm'];
			$id = Yii::app()->user->id;
			$user = User::model()->findByPk($id);
			$user->password = hashPassword($model->new_password);
			$user->auth_assignments = $user->getAuth_Assignments();
			if ($model->validate()) {
				if ($user->update()) {
					echo CJSON::encode(array(
			'status' => MsgType::SUCCESS,
			'content' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_USER_PASSWORD', 'authorization'))),
					));
					Yii::app()->end();
				}
			}
		}

		if (app()->request->isAjaxRequest) {
			echo CJSON::encode(array(
		'status' => 'render',
		'content' => $this->renderPartial('_change_password', array(
		    'model' => $model), true, true),
			));
		} else {
			throw new CHttpException(403, t('AJAX_REQUEST_IS_REQUIRED', 'messages'));
		}
	}

	//    public function actionRegister() {
	//        $this->stopJS();
	//        $model = new RegisterForgotForm('Register');
	//        $formName = 'RegisterForgotForm';
	//        if (isset($_POST[$formName])) {
	//            $model->attributes = $_POST[$formName];
	//            if ($model->validate()) {
	//                $user = User::model()->find('email = :email', array(':email' => $model->email));
	//                $user->active_code = genUniqueCode();
	//                if ($user->saveAttributes(array('active_code'))) {
	//                    $activation = domain() . $this->createUrl("/authorization/activation", array('email' => $model->email, 'active_code' => $user->active_code));
	//
	//                    $body = t('EMAIL_REGISTER_BODY', 'authorization', array(
	//                        '{name}' => $user->first_name . ' ' . $user->last_name, '{activation}' => $activation));
	//
	//                    sendMail($model->email, $body, t('EMAIL_REGISTER_SUBJECT', 'authorization'));
	//
	//                    echo CJSON::encode(array(
	//                        'status' => 'success',
	//                        'content' => t('MSG_THANK_YOU', 'authorization'),
	//                        'redirect' => url('/authorization/thank', array('type' => 'register'))
	//                    ));
	//                    Yii::app()->end();
	//                }
	//            }
	//        }
	//
	//        echo CJSON::encode(array(
	//            'status' => 'render',
	//            'content' => $this->renderPartial('_register_form', array(
	//                'model' => $model), true, true),
	//        ));
	//    }

	public function actionForgotPassword() {
		$this->stopJS();
		$model = new RegisterForgotForm('Forgot');
		$formName = 'RegisterForgotForm';
		if (isset($_POST[$formName])) {
			$model->attributes = $_POST[$formName];

			if ($model->validate(array('email'))) {
				//$user = User::model()->find('email = :email', array(':email' => $model->email));
				//Because $model->validate() == 1, $model->email existed in database surely
				$users = User::model()->findUserByEmail($model->email, false);

				if ($users == null || empty($users)) {
					/* EMAIL */
					$model->addError('email', t('MSG_NOT_EXISTED_EMAIL_FORGOT', 'authorization'));
					echo CJSON::encode(array(
			'status' => 'render',
			'content' => $this->renderPartial('_forgot_password_form', array(
			    'model' => $model), true, true),
					));
					Yii::app()->end();
				}
				$user = $users[0];

				if ($user->active) {
					$user->active_code = genUniqueCode();
					if ($user->saveAttributes(array('active_code'))) {
						$reset_pass = domain() . $this->createUrl("/authorization/resetpassword", array('email' => $model->email, 'active_code' => $user->active_code));
						$fullname = $user->first_name . ' ' . $user->last_name;
						$body = t('EMAIL_FORGOT_PASSWORD_BODY', 'authorization', array(
			    '{fullname}' => $fullname, '{reset_pass}' => $reset_pass,
			    '{username}' => $user->username, '{email}' => $user->email));

						sendMail($model->email, $body, t('EMAIL_FORGOT_PASSWORD_SUBJECT', 'authorization'));

						/* EMAIL */
						echo CJSON::encode(array(
			    'status' => MsgType::SUCCESS,
			    'content' => t('MSG_THANK_YOU', 'authorization'),
			    'redirect' => url('/authorization/thank', array('type' => 'forgotpassword'))
						));
						Yii::app()->end();
					}
				} else {
					$model->addError('email', t('MSG_NOT_ACTIVE', 'authorization'));
				}
			}
		}

		if (app()->request->isAjaxRequest) {
			echo CJSON::encode(array(
		'status' => 'render',
		'content' => $this->renderPartial('_forgot_password_form', array(
		    'model' => $model), true, true),
			));
		} else {
			throw new CHttpException(403, t('AJAX_REQUEST_IS_REQUIRED', 'messages'));
		}
	}

	public function actionResetPassword($email, $active_code) {
		$criteria = new CDbCriteria();
		$criteria->condition = 'email = :email AND active_code = :active_code';
		$criteria->params = array(':email' => $email, ':active_code' => $active_code);
		$user = User::model()->find($criteria);
		if ($user != null) {
			if (!$user->active) {
				$this->showMessage(MsgType::ERROR, t('MSG_RESET_PASSWORD_EMAIL_NOT_ACTIVED', 'authorization'));
				$this->render('message', array(
		    'title' => t('PAGE_TITLE_RESET_PASSWORD', 'authorization'),
		    'header' => t('PAGE_HEADER_RESET_PASSWORD', 'authorization'),
		    'msg' => t('MSG_CLICK_LOGIN', 'authorization')));
			} else {
				$model = new RegisterForgotForm('ResetPassword');
				$model->email = $user->email;
				$model->username = $user->username;
				$formName = 'RegisterForgotForm';
				if (isset($_POST[$formName])) {
					$model->attributes = $_POST[$formName];
					$model->scenario = RegisterForgotForm::SCENARIO_RESET_PASSWORD;
					if ($model->validate(array('new_password', 'new_password_repeat'))) {
						$user->active_code = null;
						$user->active = 1;
						$user->password = hashPassword($model->new_password);
						$user->saveAttributes(array('active_code', 'active', 'password'));
						$this->redirect(url('/authorization/thank', array('type' => 'resetpassword')));
					}
				}
				$this->render('reset_password_form', array('model' => $model));
			}
		} else {
			$this->showMessage(MsgType::ERROR, t('MSG_RESET_PASSWORD_UNSUCCESSFUL', 'authorization'));
			$this->render('message', array(
		'title' => t('PAGE_TITLE_RESET_PASSWORD', 'authorization'),
		'header' => t('PAGE_HEADER_RESET_PASSWORD', 'authorization'),
		'msg' => t('MSG_CLICK_LOGIN', 'authorization')));
		}
	}

	public function actionThank($type) {
		switch ($type) {
			case 'activation':
				$this->showMessage(MsgType::SUCCESS, t('MSG_THANK_YOU_ACTIVATION', 'authorization'));
				$this->render('message', array(
		    'title' => t('PAGE_TITLE_ACTIVATION', 'authorization'),
		    'header' => t('PAGE_HEADER_ACTIVATION', 'authorization'),
		    'msg' => t('MSG_CLICK_LOGIN', 'authorization')));
				break;
			case 'resetpassword':
				$this->showMessage(MsgType::SUCCESS, t('MSG_RESET_PASSWORD_SUCCESS', 'authorization'));
				$this->render('message', array(
		    'title' => t('PAGE_TITLE_RESET_PASSWORD', 'authorization'),
		    'header' => t('PAGE_HEADER_RESET_PASSWORD', 'authorization'),
		    'msg' => t('MSG_CLICK_LOGIN', 'authorization')));
				break;
			case 'register':
				$this->showMessage(MsgType::SUCCESS, t('MSG_REGISTRATION', 'authorization'));
				$this->render('message', array(
		    'title' => t('PAGE_TITLE_REGISTRATION', 'authorization'),
		    'header' => t('PAGE_TITLE_REGISTRATION', 'authorization'),
		    'msg' => t('MSG_REG_FORGOT_DESCRIPTION', 'authorization')));
				break;
			case 'forgotpassword':
				$this->showMessage(MsgType::SUCCESS, t('MSG_FORGOR_PASSWORD', 'authorization'));
				$this->render('message', array(
		    'title' => t('PAGE_TITLE_FORGOT_PASSWORD', 'authorization'),
		    'header' => t('PAGE_HEADER_FORGOT_PASSWORD', 'authorization'),
		    'msg' => t('MSG_REG_FORGOT_DESCRIPTION', 'authorization')));
				break;
			default:
				$this->redirect(url('/'));
				break;
		}
	}

	public function actionProfile() {
		$user = User::model()->findByPk(Yii::app()->user->id);
		$this->render('profile', array('user' => $user));
	}

}
